package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.PromotionStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.handler.GiftDrawHandler;
import com.ygqh.baby.handler.SingleGiftHandler;
import com.ygqh.baby.model.ActivitySingleGift;
import com.ygqh.baby.model.DrawPrize;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.po.YgActivityGiveaway;
import com.ygqh.baby.po.YgChannel;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgActivityGiveawayService;
import com.ygqh.baby.service.YgChannelService;
import com.ygqh.baby.service.YgProductImagesService;
import com.ygqh.baby.service.YgSkuService;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.JsonUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin/activity")
public class ActivityGiveawayController extends BaseController<Object, java.lang.Long> {

    @Autowired
    private YgActivityGiveawayService activeGiveawayService;
    @Autowired
    private YgChannelService channelService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgProductImagesService ygProductImagesService;
    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private GiftDrawHandler giftDrawHandler;
    @Autowired
    private SingleGiftHandler singleGiftHandler;

    private static final String single_gift_key = "SingleGiftActivity";

    @RequestMapping("/serachGiveaway")
    @ResponseBody
    public Map<String, Object> serachGiveaway(String q, QueryInfo queryInfo, Date startDate, Date endDate,
                                              String pStatus) {

        ResultSet<YgActivityGiveaway> resultSet = activeGiveawayService.search(queryInfo, q, startDate, endDate,
                pStatus);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("/saveGiveaway")
    @ResponseBody
    public Message saveGiveaway(String giveaway) {
        YgActivityGiveaway activityGiveaway = JsonUtils.toObject(giveaway, YgActivityGiveaway.class);
        /**
         * 判断渠道是否存在
         */
        YgChannel channel = channelService.findByCode(activityGiveaway.getSourceCode());
        if (channel == null) {
            return Message.error("100", "source值不存在");
        }

        return activeGiveawayService.saveGiveaway(activityGiveaway, SessionUtil.getCurrentUser().getTrueName());
    }

    @RequestMapping("/updateGiveaway")
    @ResponseBody
    public Message updateGiveaway(String giveaway) {
        YgActivityGiveaway activityGiveaway = JsonUtils.toObject(giveaway, YgActivityGiveaway.class);
        /**
         * 判断渠道是否存在
         */
        YgChannel channel = channelService.findByCode(activityGiveaway.getSourceCode());
        if (channel == null) {
            return Message.error("100", "source值不存在");
        }
        return activeGiveawayService.updateGiveaway(activityGiveaway, SessionUtil.getCurrentUser().getTrueName());
    }

    @RequestMapping("/getGiveawayById")
    @ResponseBody
    public YgActivityGiveaway getGiveawayById(Long id) {
        return activeGiveawayService.findById(id);
    }

    @RequestMapping("/saveSingleGift")
    @ResponseBody
    public Message saveSingleGift(String singleGift) {
        AdminUser user = SessionUtil.getCurrentUser();

        ActivitySingleGift gift = JsonUtils.toObject(singleGift, ActivitySingleGift.class);


        gift.setHandler(user.getTrueName());
        gift.setUpdateTime(new Date());

        return singleGiftHandler.saveSingleGift(gift);
    }

    @RequestMapping("/deleteSingleGift")
    @ResponseBody
    public Message deleteSingleGift(boolean isChannel, String sourceCode) {
        return singleGiftHandler.deleteSingleGift(isChannel, sourceCode);
    }

    private String addSingleGiftToRedis(ActivitySingleGift gift) {
        List<ActivitySingleGift> list = null;
        String res = redisDao.get(single_gift_key);
        if (StringUtils.isNotBlank(res)) {
            list = JSON.parseArray(res, ActivitySingleGift.class);
            Iterator<ActivitySingleGift> it = list.iterator();
            while (it.hasNext()) {
                ActivitySingleGift next = it.next();
                // 已过期
                long millis = DateConvertUtils.getDateStart(new Date()).getTime();
                if (millis > next.getEndDate().getTime() || next.getSourceCode().equals(gift.getSourceCode())) {
                    it.remove();
                }
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<ActivitySingleGift>();
        }
        list.add(gift);
        return redisDao.set(single_gift_key, JSON.toJSONString(list), 0);

    }

    @RequestMapping("/getSingleGift")
    @ResponseBody
    public Message getSingleGift(String sourceCode, Boolean isChannel) {
        ActivitySingleGift activitySingleGift = singleGiftHandler.getActivitySingleGift(sourceCode, isChannel);
        return Message.success(activitySingleGift);
    }

    @RequestMapping("/getSingleGiftList")
    @ResponseBody
    public Map<String, Object> getSingleGiftList(String q, Boolean isChannel, PromotionStatus pStatus, Date startDate, Date endDate) {
        List<ActivitySingleGift> activitySingleGiftList = singleGiftHandler.getActivitySingleGiftList(isChannel);

        List<ActivitySingleGift> result = activitySingleGiftList.stream().filter(gift -> {
            if (StringUtils.isNotBlank(q)) {
                return q.equals(gift.getSourceCode());
            }
            if (pStatus != null) {
                return gift.getPromotionStatus().equals(pStatus);
            }
            if (startDate != null) {
                return gift.getStartDate().compareTo(startDate) >= 0;
            }
            if (endDate != null) {
                return gift.getEndDate().compareTo(endDate) <= 0;
            }
            return true;
        }).collect(Collectors.toList());
        ResultSet<ActivitySingleGift> activitySingleGiftResultSet = new ResultSet<>(activitySingleGiftList.size(), result);

        return activitySingleGiftResultSet.toDatatables(null);
    }

    private static final String sourceCode = "DRAW_PRIZE_SOURCE";

    @RequestMapping("/saveDrawPrize")
    @ResponseBody
    public Message saveDrawPrize(String drawPrize) {
        AdminUser user = SessionUtil.getCurrentUser();
        if (StringUtils.isNotBlank(drawPrize)) {
            DrawPrize prize = JSON.parseObject(drawPrize, DrawPrize.class);
            prize.setHandler(user.getTrueName());
            prize.setUpdateTime(new Date());

            /*prize.getPrizeItems().forEach(p -> {
                if (p.getType().equals(Type.Goods)) {
                    YgSku sku = ygSkuService.findBySkuCode(p.getRelationCode(), PromotionType.ManZeng);
                    YgProductImages images = ygProductImagesService.findMainImgByProductId(sku.getProductId());
                    p.setImgUrl(images.getImagePath());
                }

            });*/
            String json = JSON.toJSONString(prize);

            //Long diffDays = DateConvertUtils.diffDayes(prize.getStartDate(), prize.getEndDate());
            //long expire = (diffDays + 1) * 24 * 60 * 60 * 1000;
            String set = redisDao.set(RedisConstant.PRIZE_ITEM_KEY, json, 0);
            redisDao.set(sourceCode, prize.getSourceCode(), 0);
            return Message.success(set);
        }
        return Message.error("提交数据为空", drawPrize);
    }

    @RequestMapping("/getDrawPrize")
    @ResponseBody
    public Message getDrawPrize() {
        String res = redisDao.get(RedisConstant.PRIZE_ITEM_KEY);
        if (StringUtils.isNotBlank(res)) {
            DrawPrize prize = JSON.parseObject(res, DrawPrize.class);

            return Message.success(prize);
        }
        return Message.error("提交数据为空", null);
    }

    /**
     * 新年有礼，开奖接口
     *
     * @param sourceCode 批次
     * @return Message
     */
    @RequestMapping("/drawNewYearGift")
    @ResponseBody
    public Message getDrawPrizeV2(String sourceCode) {
        String s = giftDrawHandler.drawNewYearGift(sourceCode);
        return Message.success(s);
    }

}
